package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Record;
import com.kaishengit.entity.User;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.Page;
import com.kaishengit.util.RowMapper;

public class RecordDao {
	private DBHelp<Record> db = new DBHelp<Record>();
	public Page<Record> findContactAndRecord(String id,Page<Record> page) {
		StringBuilder sql = new StringBuilder();
		sql.append("select tr.id,tr.content,tr.createtime,tr.t_contact_id,tr.t_user_id ,tu.username from t_record as tr ");
		sql.append("left join t_user as tu on tu.id = tr.t_user_id ");
		sql.append("left join t_contact as tc on tc.id = tr.t_contact_id ");
		sql.append("where tr.t_contact_id = ? order by createtime desc limit ?,?");
		List<Record> list = db.executeQueryForList(sql.toString(), new RecordRowMapper(), id,page.getOffest(),page.getPageSize());
		page.setList(list);
		return page;
	}
	private class RecordRowMapper implements RowMapper<Record>{

		public Record mapRow(ResultSet rs) throws SQLException {
			Record r = new Record();
			r.setContactId(rs.getString("t_contact_id"));
			r.setId(rs.getString("id"));
			r.setCreatetime(rs.getString("createtime"));
			r.setUserid(rs.getString("t_user_id"));
			r.setContent(rs.getString("content"));
			User user = new User();
			user.setId(rs.getString("t_user_id"));
			user.setUsername(rs.getString("username"));
			r.setUser(user);
			
			return r;
		}
		
	}
	public void saveRecord(User user, String content, String id,
			String createtime, String id2) {
		String sql = "insert into t_record (id,content,createtime,t_contact_id,t_user_id) values(?,?,?,?,?)";
		db.executeSQL(sql, id,content,createtime,id2,user.getId());
		
	}
	public long getCount(String id) {
		String sql = "select count(*) from t_record where t_contact_id = ?";
		return (Long) db.executeForFunction(sql, id);
	}
	public void delRecordByContactId(String id) {
		String sql = "delete from t_record where t_contact_id = ?";
		db.executeSQL(sql, id);
		
	}
}
